package com.xgame.util;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.xgame.mybatis.model.User;

public class ProtobufResponseUtil {

	/**
	 * 返回处理
	 */
	public static void protobufResponse(byte[] buf, HttpServletResponse response)
			throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.getOutputStream().write(buf);
	}

//	/**
//	 * 获取State
//	 * @param flag
//	 *            标示 若true表示成功 false 为失败
//	 * @param message
//	 *            返回的信息提示
//	 */
//	public static State getState(boolean flag, String message) {
//
//		StateProto.State.Builder builder = StateProto.State.newBuilder();
//		if (flag) {
//			builder.setCode(1).setMsg(message);
//		} else {
//			builder.setCode(0).setMsg(message);
//		}
//		State state = builder.build();
//		return state;
//	}

	/**
	 * 基于反射将value类中和obj类相同的属性赋值给obj类 当value类中为Date类型时obj中为long型 obj 是一个builder
	 * 如：ActivityProto.Activity.newBuilder() value类为对象 如 VipPromotionActivity
	 * activity = new VipPromotionActivity(); activity.setId(1);
	 * activity.setName("ddddd"); activity.setCreateTime(new Date());
	 * 
	 * 结果为对应builder的类 结果为ActivityProto.Activity 测试参考主方法 public static void
	 * main(String[] args){}
	 * 
	 */
	public static Object protobufResponseValue(Object obj, Object value)
			throws Exception {
		Field[] fields = value.getClass().getDeclaredFields();
		Method method = obj.getClass().getDeclaredMethod("getDescriptor");
		Descriptor desObj = (Descriptor) method.invoke(obj);
		List<FieldDescriptor> descriptors = desObj.getFields();
		for (int i = 0; i < descriptors.size(); i++) {
			for (int j = 0; j < fields.length; j++) {
				fields[j].setAccessible(true);
				String valueType = fields[j].getType().getName();
				String type = descriptors.get(i).getJavaType().name();
				String fieldsName = fields[j].getName();
				String descriptorsName = descriptors.get(i).getName();
				if (fieldsName.equals(descriptorsName)) {
					Object valueObj = value
							.getClass()
							.getMethod(getGetMethod(fieldsName), new Class[] {})
							.invoke(value);
					if (valueObj != null) {
						if (valueType.equals("java.util.Date")) {
							Date valuedate = (Date) valueObj;
							valueObj = valuedate.getTime();
						}
						obj.getClass()
								.getMethod(getSetMethod(fieldsName),
										new Class[] { getJavaType(type) })
								.invoke(obj, valueObj);
					}
					break;
				}
			}
		}
		Object result = obj.getClass().getDeclaredMethod("build").invoke(obj);
		return result;
	}

	/**
	 * 判断类型
	 * 
	 * @param type
	 * @return
	 */
	private static Class<?> getJavaType(String type) {
		type = type.toLowerCase();
		Class<?> clazz = null;
		if (type.equals("string")) {
			clazz = String.class;
		} else if (type.equals("int")) {
			clazz = int.class;
		} else if (type.equals("Long")) {
			clazz = Long.class;
		} else if (type.equals("long")) {
			clazz = long.class;
		} else if (type.equals("Integer")) {
			clazz = Integer.class;
		}
		return clazz;
	}

	/***
	 * 根据属性拼接成set方法
	 */
	private static String getSetMethod(String name) {
		if (!isEmpty(name)) {
			char c = name.charAt(0);
			if (!Character.isUpperCase(c)) {
				c = (char) (c - 32);
			}
			name = "set" + c + name.substring(1);
			return name;
		}
		return null;
	}

	/***
	 * 根据属性拼接成get方法
	 */
	private static String getGetMethod(String name) {
		if (!isEmpty(name)) {
			char c = name.charAt(0);
			if (!Character.isUpperCase(c)) {
				c = (char) (c - 32);
			}
			name = "get" + c + name.substring(1);
			return name;
		}
		return null;
	}

	/**
	 * 判断是否为空
	 */
	private static boolean isEmpty(String str) {
		if (str == null || str.equals("")) {
			return true;
		}
		return false;
	}

	/**
	 * 
	 * 测试
	 * 
	 */
	public static void main(String[] args) throws Exception {
		System.out.println(getSetMethod("name"));
		User activity = new User();
		activity.setUid(1l);
		activity.setUserName("ddddd");
		activity.setCreateTime(new Date());
		toString(activity);
	}

	public static void toString(Object o) throws Exception {
		Field[] fields = o.getClass().getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			String name = fields[i].getName();
			if (!name.equals("serialVersionUID")) {
				Object value = o.getClass()
						.getMethod(getGetMethod(name), new Class[] {})
						.invoke(o);
				System.out.println(name + ":" + value);
			}
		}
	}
}
